import { defineStore } from "pinia";
import { userKey } from "./keys";

interface IUserState {
  menus: IMenuModel[];
  username: String;
}

type menu = IMenuModel & { children: IMenuModel[] };
export const useUserStore = defineStore(userKey, {
  state(): IUserState {
    return {
      menus: [],
      username: "",
    };
  },
  getters: {
    routes() {
      let menus: menu[] = [];
      // 找到所有的1级
      menus = this.menus
        .filter((item) => item.parentId === 0)
        .map((item) => ({
          ...item,
          children: [],
        }));

      // 继续把2级加入对应的1级的children
      this.menus.forEach((sub) => {
        const p = menus.find((item) => item.id === sub.parentId);
        if (p) {
          p.children.push(sub);
        }
      });
      return menus;
    },
    // 得到当前用户的所有权限的字符串
    Permissions(): string[] {
      return this.menus.map((item) => item.name);
    },
  },
});
